#!/usr/bin/env perl

use v5.10.1;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Encode;
use strict;
use warnings;

my %cmdLs = ("s"=>"ssh-copy-id", "mdb"=>"140后台:dbmd5", "md5"=>"得到md5的值", 
			 "t"=>"输入时间截转换时间", "q"=>"退出...",
			 "u"=>"得到当前的时间戳","cd"=>"待定...");
my @arr=();

show_cmd_list(); # 显示命令界面...

while (<>) {
	chomp;
	if( exists($cmdLs{$_} ) ){
		my $cmd = $cmdLs{$_};

		# say "Matched:" . $cmd;
		if ($_ eq "s") 		{	ssh_copy_id(); } 
		elsif ($_ eq "mdb") {	dbmd5(); 	   } 
		elsif ($_ eq "md5") {	md5val(); 	   } 
		elsif ($_ eq "t") 	{	timeformat();  } 
		elsif ($_ eq "u") 	{	unixtimes();  } 
		elsif ($_ eq "q") 	{	exit();   	   } #退出 
		

		print "请输入命令:";
	}
	else{
		print "没有这个命令,请重新输入:";
	}
}

# 显示命令界面...
sub show_cmd_list{
	my $count =0;

	say "======== 运维工具集 ================";
	print "+------------------------------------------------------------------------------+\n";

	foreach my $key (sort keys %cmdLs){
	# while(my($key, $value) = each %cmdLs)  {
		my $value = $cmdLs{$key};
		$count++;
		push (@arr, "$key:$value"); #把值添加到arr数组

	 	if (($count%5)==0){	print_cmd(@arr);	} 	
	}
	print_cmd(@arr); 
	say "+------------------------------------------------------------------------------+";
	print "请输入命令:";
}

# 输出命令列表
sub print_cmd{

 	while($_ =shift(@arr)){
 		printf "%-1s %-13s", "|", $_; 	
	}
	printf "%-1s \n", "|";	
}

sub ssh_copy_id{

	say "请按格式输入:用户名 ip 端口号(默认为32200), 例子:admin 10.1.81.196 32200";

	while (<>) {
		chomp;

		my ($uname, $ip, $port) = split(/ /);

		$port //= '32200'; # 如果$port为undef, 默认为32200

		say "用户名=$uname, IP=$ip, port=$port";

		my $recode = system("ssh-copy-id $uname\@$ip -p $port 2>&1 1>/dev/null");
	}	
}

# 生成后台md5值
sub dbmd5{
	use POSIX qw(strftime);
	

  	my $now_string = strftime "%Y%m%d%H", localtime;

	say 'URL:http://fx140.kugou.com/fx6gl/DbView.php';
 	say md5_hex($now_string.'mmkgfx');
}

# 生成MD5的值
sub md5val{
	print "请输入要md5的值:";
	my $val = <>;
	chomp;
	say md5_hex($val);
}

sub timeformat {
	use POSIX qw/ strftime /;

	my $t = @_;

	print "请输入时间戳:";
	my $val = <>;

	say strftime("%Y-%m-%d %H:%M:%S", localtime($val));
	
}

#当前的时间戳
sub unixtimes{
	# system("date '+%s'");
	my $now = `date '+%s'`;

	print $now;
	say strftime("%Y-%m-%d %H:%M:%S", localtime($now));
}